import React from 'react';
import ReactDom from 'react-dom';
import { changeNav } from '../../../actions';
import { connect } from 'react-redux';
import { Button, List, WhiteSpace, Switch, InputItem, Toast, DatePicker } from 'antd-mobile';
import { ajaxPost } from 'wxAjaxUtil';
import moment from 'moment';
// import CSSModules from 'react-css-modules';
import hhistory from '../../../history';
import styles from './wsConfig.less';
const Item = List.Item;
// @CSSModules(styles, { allowMultiple: true })
let weeks = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
let time = moment('00:00', 'HH:mm').utcOffset(8);
let endTime = moment('23:59', 'HH:mm').utcOffset(8);
let minTime = moment('00:00', 'HH:mm').utcOffset(8);
let storeInfo = null;
class WsConfig extends React.Component {
    constructor(props) {
        super(props);
        this.onErrorClick = this.onErrorClick.bind(this);
        this.wsOnChange = this.wsOnChange.bind(this);
        this.qsOnChange = this.qsOnChange.bind(this);
        this.maxDayOnChange = this.maxDayOnChange.bind(this);
    }
    state = {
        isChecked: false, //外送是否开启标识
        wsFee: 0,  //外送费用
        qsPrice: '',//起送价格
        maxDay: '',//外送最大天数
        ishdfk: 0,  //支持货到付款，0-否，1-是
        ispsfree: 0, //免配送费标识，0-未开通，1-开通
        freeDePrice: 0, //免配送费金额
        wsggValue: '', //注意事项
        configTimes: [], //外送时间范围
        delayDeTime: 0, //延迟外送时间
        selectWeek: [], //星期选择
        startTime: time,
        endTime: endTime,
        minTime: minTime,

        wsHasError: false,
        qsHasError: false,
        maxDayHasError: false

    }

    componentWillMount() {
        var that = this;
        var { storeCode } = this.props.params;
        if (storeCode) {
            storeInfo = [storeCode];
        } else {
            var locationStoreCode = this.props.location.state.storeCode;
            storeInfo = locationStoreCode;
        }
        if (!storeCode) {
            return;
        }
        /* var { selectTimes } = this.props;
        if (selectTimes.length) {
            var time = selectTimes[selectTimes.length -1];
            this.setState({ configTimes: selectTimes });
        } */
        ajaxPost('/o2o/sly/conf/load/zhct/delivery', { 'storeCode': storeCode }, 'wxApiPath').then(res => {
            if (res.errorCode == 200) {
                var loadData = res.data;
                console.log(22222222)
                console.log(loadData);
                /* $scope.isChecked = changeToBool(loadData.deliveryFlg);
                $scope.wsFee = loadData.dePrice;
                $scope.qsPrice = loadData.minPrice;
                $scope.maxDay = loadData.deMaxDay;
                $scope.ishdfk = changeToBool(loadData.hdfkFlg);
                $scope.ispsfree = changeToBool(loadData.freeDeFlg);
                $scope.freeDePrice = loadData.freeDePrice;
                $scope.wsggValue = loadData.remark;
                $scope.configTimes = loadData.deRange == null ? [] : loadData.deRange;
                $scope.delayDeTime = loadData.delayDeTime; */
                that.setState({
                    isChecked: !!loadData.deliveryFlg,
                    wsFee: loadData.dePrice,
                    qsPrice: loadData.minPrice,
                    maxDay: loadData.deMaxDay,
                    ishdfk: !!loadData.hdfkFlg,
                    ispsfree: !!loadData.freeDeFlg,
                    freeDePrice: loadData.freeDePrice,
                    wsggValue: loadData.remark,
                    configTimes: loadData.deRange == null ? [] : loadData.deRange,
                    delayDeTime: loadData.delayDeTime
                })
            } else {
                Toast.fail(res.errorText, 2);
            }
        }).catch(err => {
            Toast.fail(err.errorText, 2);
        });
    }
    componentDidMount() {
        this.props.tochangeNav({
            title: "外送设置", rbtn: [
                <Button key="1" type="primary" inline onClick={() => this.saveDataEvent()} size="small">确定</Button>
            ]
        });
    }
    addTime() {
        var { startTime, endTime, selectWeek } = this.state;
        if (!selectWeek.length || !startTime || !endTime) {
            Toast.fail('请选择配送时间或者日期', 2);
            return;
        }
        var { configTimes } = this.state;
        var _startTime = moment(startTime).format('HH:mm');
        var _endTime = moment(endTime).format('HH:mm');
        var statTime = new Date('01/10/2007 ' + startTime.hours() + ':' + startTime.minutes() + ':' + startTime.seconds());
        var endTime = new Date('01/10/2007 ' + endTime.hours() + ':' + endTime.minutes() + ':' + startTime.seconds());
        var dateArr = [];
        var tempArr = [];
        var tempStr2 = '';
        var bool = false;
        var updateTime = false;
        var pushTimeStr = _startTime + '-' + _endTime;
        weeks.forEach((w, i) => {
            if (selectWeek.indexOf(i) > -1) {
                dateArr.push(pushTimeStr);
            } else {
                dateArr.push("");
            }
        });

        dateArr.some((week, i) => {
            var timeStr = '';
            if (week) {
                if (!configTimes.length) {
                    bool = false;
                }

                configTimes.some(items => {
                    var dayTimeObj = items[i];
                    var matchTime = dayTimeObj;
                    updateTime = false;
                    if (matchTime) {//录入时间
                        var _matchStatr = matchTime.split('-')[0];
                        var _matchEnd = matchTime.split('-')[1];
                        var _matchStatrTime = new Date('01/10/2007 ' + _matchStatr);
                        var _matchEndTime = new Date('01/10/2007 ' + _matchEnd);
                        if (!(statTime.getTime() > _matchEndTime.getTime() || endTime.getTime() < _matchStatrTime.getTime())) { //验证规则 当前开始时间 应该大于之前的结束时间  或者 当前的结束时间 小于 之前的开始时间才能通过
                            bool = true;
                            return true;
                        }
                    } else {//前面的值没有时间  将新选择的时间 更新上去
                        updateTime = true;
                        // timeStr = '';
                        items[i] = pushTimeStr;
                        return true;
                    }
                    return false;
                });

                if (!bool) {
                    if (!updateTime) {
                        timeStr = pushTimeStr;
                    }
                }
            }

            if (bool) {
                tempArr.length = 0;
                return true;
            } else {
                tempArr.push(timeStr);
            }
        });


        if (bool) {
            Toast.fail('时间段已经包含了', 2);
        } else {
            var hasValue = false;
            hasValue = tempArr.some(val => {
                if (val) {
                    return true;
                }
                return false;
            });

            if (hasValue) {//
                tempArr[tempArr.length] = pushTimeStr;
                configTimes.push(tempArr);
            }
            this.setState({ configTimes: configTimes });
        }
    }
    toggleWeek(i) {
        var { selectWeek } = this.state;
        var index = selectWeek.indexOf(i);
        if (index > -1) {
            selectWeek.splice(index, 1);
        } else {
            selectWeek.push(i);
        }
        this.setState({ selectWeek: selectWeek });
    }
    timeChange(date, num) {

        if (num == 1) {
            var startTime = moment(date).add(1, 'm');
            this.setState({ [num == 1 ? 'startTime' : 'endTime']: date, 'minTime': startTime, endTime: startTime });
        } else {
            this.setState({ [num == 1 ? 'startTime' : 'endTime']: date });
        }

    }
    saveDataEvent() {//将每组的最后一个显示日期去掉 
        var { configTimes } = this.state;
        configTimes.forEach(time => {
            if (time.length > 7) {
                time.pop();
            }
        });
        console.log(configTimes)
        /*  ajaxPost('/o2o/sly/conf/apply/zhct/order', saveData, 'wxApiPath').then(res => {
             if (res.errorCode == 200) {
                 Toast.success('保存成功', 2);
             } else {
                 Toast.fail('操作失败，请重试', 2);
             }
         }).catch(err => {
             Toast.fail(err.message, 2);
         }); */

    }


    setValue(evt, key) {
        var target = evt.target;
        var v = target.value;
        this.setState({ [key]: v });
    }

    previewTime(index) {
        var time = this.state.configTimes;
        time.splice(index, 1);
        this.setState({ configTimes: time });
    }

    onErrorClick = () => {
        if (this.state.wsHasError) {
            Toast.info('请输入0~99之间的数字！');
        }
        if (this.state.qsHasError) {
            Toast.info('请输入1~99之间的数字！');
        }
        if (this.state.maxDayHasError) {
            Toast.info('请输入1~9之间的数字！');
        }
    }
    wsOnChange = (value) => {
        if (isNaN(Number(value)) || Number(value) < 0 || Number(value) > 99) {
            this.setState({
                wsHasError: true,
            });
        } else {
            this.setState({
                wsHasError: false,
            });
        }
        this.setState({
            wsFee: value
        });
    }
    qsOnChange = (value) => {
        if (isNaN(Number(value)) || Number(value) < 1 || Number(value) > 99) {
            this.setState({
                qsHasError: true,
            });
        } else {
            this.setState({
                qsHasError: false,
            });
        }
        this.setState({
            qsPrice: value
        });
    }
    maxDayOnChange = (value) => {
        if (isNaN(Number(value)) || Number(value) < 1 || Number(value) > 9) {
            this.setState({
                maxDayHasError: true,
            });
        } else {
            this.setState({
                maxDayHasError: false,
            });
        }
        this.setState({
            maxDay: value
        });
    }


    render() {
        let ctrl = this;
        return (
            <div>
                <WhiteSpace size="lg" />
                <List>
                    <Item arrow="horizontal" extra={<div className={styles.red}>{storeInfo.length}个</div>}><span className={styles.titleSize}>已选门店</span></Item>
                </List>
                <WhiteSpace size="lg" />
                <List>
                    <Item extra={<Switch className="mySwitch" checked={this.state.isChecked} onClick={(v) => { this.setState({ isChecked: !this.state.isChecked }) }} />}>
                        <span className={styles.titleSize}>开启外送</span>
                    </Item>
                </List>
                <WhiteSpace size="lg" />
                <List renderHeader="基本信息" className="whiteHeader">

                    <div><span className={styles.wsFee}>外送费用</span><InputItem type="money" className="customInput" clear error={this.state.wsHasError} onErrorClick={this.onErrorClick} onChange={this.wsOnChange} value={this.state.wsFee} />元</div>
                    <div><span className={styles.wsFee}>起送价格</span><InputItem type="money" className="customInput" clear error={this.state.qsHasError} onErrorClick={this.onErrorClick} onChange={this.qsOnChange} value={this.state.qsPrice} />元</div>
                    <div><span className={styles.wsFee}>最大配送天数</span><InputItem type="money" className="dayInput" clear error={this.state.maxDayHasError} onErrorClick={this.onErrorClick} onChange={this.maxDayOnChange} value={this.state.maxDay} />天</div>

                    <Item extra={<Switch className="mySwitch" checked={this.state.ishdfk} onClick={(v) => { this.setState({ ishdfk: !this.state.ishdfk }) }} />}>
                        <span className={styles.titleSize}>货到付款</span>
                    </Item>
                    <Item extra={<Switch className="mySwitch" checked={this.state.ispsfree} onClick={(v) => { this.setState({ ispsfree: !this.state.ispsfree }) }} />}>
                        <span className={styles.titleSize}>免费配送</span>
                    </Item>
                    <Item>
                        <span className={styles.titleSize}>满</span>
                        <input type="text" className={styles.freeDePrice} defaultValue={this.state.freeDePrice} onChange={(evt) => { this.setValue(evt, 'freeDePrice') }} />
                        <span className={styles.titleSize}>元，免费配送</span>
                    </Item>
                </List>
                <WhiteSpace size="lg" />
                <List renderHeader="外送公告" className="whiteHeader">
                    <Item multipleLine>
                        <textarea placeholder="200字以内" className={styles.dishTips} value={this.state.wsggValue} onChange={(evt) => { this.setValue(evt, 'wsggValue') }}></textarea>
                    </Item>
                </List>

                <WhiteSpace size="lg" />

                <List renderHeader={<div className={styles.wsTextHeader}><span>外送时间段设置</span><span className={styles.btnWrap2}><Button type="primary" inline size="small" onClick={() => this.addTime()}>添加</Button></span></div>} className="whiteHeader">
                    <List.Item multipleLine>
                        <div className={styles.weekBtnWrap}>
                            {
                                weeks.map((text, i) => (
                                    <div key={i} className={this.state.selectWeek.indexOf(i) > -1 ? styles.weekActiveBtn : styles.weekBtn} onClick={() => this.toggleWeek(i)}>{text}</div>
                                ))
                            }
                        </div>
                    </List.Item>
                    <DatePicker
                        mode="time"
                        title="选择开始时间"
                        extra="开始时间"
                        value={this.state.startTime}
                        onChange={(date) => this.timeChange(date, 1)}
                    >
                        <List.Item arrow="horizontal" ><span className={styles.titleSize}>开始时间</span></List.Item>
                    </DatePicker>

                    <DatePicker
                        mode="time"
                        title="选择结束时间"
                        extra="结束时间"
                        value={this.state.endTime}
                        onChange={(date) => this.timeChange(date, 2)}
                        minDate={this.state.minTime}
                    >
                        <List.Item arrow="horizontal"><span className={styles.titleSize}>结束时间</span></List.Item>
                    </DatePicker>
                </List>
                <div className={styles.dateTable}>
                    <table className={this.state.configTimes.length ? '' : styles.textHide}>
                        <thead>
                            <th>一</th>
                            <th>二</th>
                            <th>三</th>
                            <th>四</th>
                            <th>五</th>
                            <th>六</th>
                            <th>日</th>
                            <th>操作</th>
                        </thead>
                        <tbody>
                            {
                                this.state.configTimes.map((items, i) => {
                                    return <tr key={i} >

                                        {
                                            items.map((time, j) => {
                                                if (j < (items.length - 1)) {
                                                    return <td key={j}><span className="weekItems">{time}</span></td>
                                                }
                                            })
                                        }
                                        <td><Button key="1" type="primary" inline onClick={() => this.previewTime(i)} size="small">删除</Button></td>
                                    </tr>
                                })
                            }
                        </tbody>

                    </table>
                </div>
            </div>
        )
    }

}

const mapStateToProps = (state) => {
    return {
        selectTimes: state.wxSmartdrs.wxTimeSelectData
    }
}
const mapDispatchToProps = (dispatch) => ({
    tochangeNav: navogj => dispatch(changeNav(navogj))
})

export default connect(mapStateToProps, mapDispatchToProps)(WsConfig)